package com.ruoyi.stream.framework.core.workDomain;

import com.ruoyi.stream.framework.core.IOTask;
import com.ruoyi.stream.framework.core.IOTaskGroup;
import com.ruoyi.stream.framework.core.workDomain.io.ConsumeIO;
import com.ruoyi.stream.framework.core.workDomain.io.IOBehavior;
import com.ruoyi.stream.framework.model.configBuilder.single.SingleIOTaskConfig;
import io.netty.channel.Channel;

import java.io.IOException;
import java.io.InputStream;


public class SingleIOTask extends IOTask<SingleIOTaskGroup, SingleIOTaskConfig> {
    private final InputStream inputStream;

    private volatile int cacheLength;

    private volatile byte[] cache;

    private volatile long fullLength;

    private volatile long readLength;



    public InputStream getInputStream() {
        return inputStream;
    }

    public int getCacheLength() {
        return cacheLength;
    }

    public void setCacheLength(int cacheLength) {
        this.cacheLength = cacheLength;
    }

    public byte[] getCache() {
        return cache;
    }

    public void setCache(byte[] cache) {
        this.cache = cache;
    }

    public long getFullLength() {
        return fullLength;
    }

    public void setFullLength(long fullLength) {
        this.fullLength = fullLength;
    }

    public long getReadLength() {
        return readLength;
    }


    public void setReadLength(long readLength) {
        this.readLength = readLength;
    }


    public SingleIOTaskGroup getGroup() {
        return group;
    }

    public SingleIOTask(InputStream inputStream, int cacheLength, IOBehavior cancel, IOBehavior read, IOBehavior pause, ConsumeIO write, Channel channel) {
        this.inputStream = inputStream;
        this.cacheLength= cacheLength;
        this.cache = new byte[cacheLength];
        this.cancel = cancel;
        this.read = read;
        this.currentBehavior = read;
        this.pause = pause;
        this.write = write;
        this.channel = channel;
        this.readLength = 0;
        try {
            this.fullLength = inputStream.available();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public IOBehavior getCurrentBehavior() {
        return currentBehavior;
    }

    @Override
    public void config(SingleIOTaskConfig ioConfig) {
    }

    public void pause(){
        this.currentBehavior = this.pause;
    }

    public void cancel(){
        this.currentBehavior = this.cancel;
    }

    public void processRead(){
        this.currentBehavior = this.read;
    }

    public void finish(){
        this.currentBehavior = this.cancel;
    }

    @Override
    public void setGroup(SingleIOTaskGroup ioTaskGroup) {
        this.group = ioTaskGroup;
        group.addTask(this);
    }
}
